<template>
  <div class="register-container">
    <div class="register-card">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>用户注册</span>
          </div>
        </template>
        
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          label-width="80px" 
          @submit.prevent="handleRegister"
        >
          <el-form-item label="登录账号" prop="username">
            <el-input 
              v-model="form.username" 
              placeholder="请输入登录账号"
              clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="昵称" prop="nickName">
            <el-input 
              v-model="form.nickName" 
              placeholder="请输入昵称"
              clearable
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="form.email" 
              placeholder="请输入邮箱地址"
              clearable
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-row :gutter="10">
              <el-col :span="14">
                <el-input 
                  v-model="form.captcha" 
                  placeholder="请输入验证码"
                  clearable
                />
              </el-col>
              <el-col :span="10">
                <img 
                  :src="captchaImage" 
                  @click="getCaptcha" 
                  class="captcha-image" 
                  width="130px"
                  height="40px"
                  alt="验证码"
                  v-if="captchaImage"
                />
                <el-button 
                  type="default" 
                  @click="getCaptcha" 
                  class="captcha-btn" 
                  :loading="captchaLoading"
                  v-else
                >
                  获取验证码
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              native-type="submit" 
              :loading="loading"
              style="width: 100%"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-link">
          已有账号？<el-button type="text" @click="$router.push('/login')">立即登录</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 定义响应式数据
const formRef = ref()
const loading = ref(false)

const form = reactive({
  username: '',
  password: '',
  nickName: '',
  email: '',
  phone: '',
  captcha: ''
})

// 验证码相关状态
const captchaImage = ref('')
const captchaLoading = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, message: '登录账号至少3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, message: '昵称至少2个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 1, max: 6, message: '验证码长度为4-6位', trigger: 'blur' }
  ]
}

// 路由实例
const router = useRouter()

// 获取验证码
const getCaptcha = async () => {
  if (!form.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  // 验证手机号格式
  const phoneRule = rules.phone[1]
  if (!phoneRule.pattern.test(form.phone)) {
    ElMessage.warning('请输入有效的手机号')
    return
  }
  
  captchaLoading.value = true
  
  try {
    const response = await request.get('/public/register/captcha', {
      params: {
        phone: form.phone
      }
    })
    
    if (response.code === 200 && response.data) {
      // 设置验证码图片，base64字符串需要添加data:image/png;base64,前缀
      captchaImage.value = 'data:image/png;base64,' + response.data
    } else {
      ElMessage.error('获取验证码失败')
    }
  } catch (error) {
    ElMessage.error('获取验证码失败，请稍后重试')
    console.error('获取验证码错误:', error)
  } finally {
    captchaLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitForm()
    }
  })
}

// 提交表单
const submitForm = async () => {
  loading.value = true
  
  try {
    // 这里应该调用实际的注册API
    // 示例：await registerApi(form)
    // await new Promise(resolve => setTimeout(resolve, 2000))
    let res=await request({
      url: "/public/register/"+form.captcha,
      method: 'post',
      data: form
    })

    // ElMessage.success(res.message)
    router.push('/login')
  } catch (error) {
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  object-fit: contain;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
}

.captcha-btn {
  width: 100%;
  height: 40px;
}

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 500px;
}

.card-header {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  padding: 20px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 30px;
}
</style>